package com.example.micro.netty.server.tcpprotocal;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;

/**
 * tcp粘包拆包 client-handler
 *
 * @author Code Farmer
 * @create 2021/3/7 7:07 下午
 */
public class MyTcpProtocalClientHandler extends SimpleChannelInboundHandler<MessageProtocal> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //使用客户端发送十条数据 "今天有点儿冷，咱们吃火锅！"
        for (int i = 0; i < 5; i++) {
            String msg = "今天有点儿冷，咱们吃火锅！" + i;
            byte[] content = msg.getBytes(StandardCharsets.UTF_8);
            int len = content.length;

            //创建协议包对象
            MessageProtocal messageProtocal =
                    new MessageProtocal(len, content);
            ctx.writeAndFlush(messageProtocal);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocal messageProtocal) throws Exception {
        int len = messageProtocal.getLen();
        byte[] content = messageProtocal.getContent();

        System.out.println("客户端接收到信息如下：");
        System.out.println("长度：" + len);
        System.out.println("内容：" + new String(content, StandardCharsets.UTF_8));

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
